package com.matrix.tool.ui.tool

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.activity.enableEdgeToEdge
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.matrix.basecore.base.BaseActivity
import com.matrix.basecore.constant.Constant
import com.matrix.tool.databinding.ActivityTestCorpBinding
import com.matrix.tool.ui.tool.dialog.RatioPopWin
import com.matrix.tool.utils.cropper.BitmapUtil
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException

@Route(path = Constant.ARouterPath.CorpTestActivityPath)
class CorpTestActivity : BaseActivity<ActivityTestCorpBinding>() {
    private var mAspectRatioX = 1
    private var mAspectRatioY = 1
    private var screen_width: Int = 100
    private var screen_height: Int = 100
    private var path: ArrayList<String> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
    }

    override fun getViewBinding(): ActivityTestCorpBinding {
        enableEdgeToEdge()
        return ActivityTestCorpBinding.inflate(layoutInflater)
    }

    override fun initView() {
        val listExtra = intent.getStringArrayListExtra(Constant.ARouterString.PATH)

        if (listExtra != null) {
            path = listExtra
        }
        LogUtils.i(path)
        mViewBinding.civ.post {
//            cropImage(path[0])
        }
    }

    override fun initData() {
        mViewBinding.civ.post {
            var rpw = RatioPopWin(this, mViewBinding.main, object : RatioPopWin.RatioClickback {
                override fun onRatio(x: Int, y: Int) {
                    mAspectRatioX = x
                    mAspectRatioY = y
                    LogUtils.i(path[0])
                    cropImage(path[0])
                }
            })
            rpw.setCropRatio()
        }
    }

    override fun initListener() {
        mViewBinding.title.ivBack.setOnClickListener { finish() }

        mViewBinding.ivTest.setOnClickListener {
            cropImage(path[0])
        }
    }

    private fun cropImage(mFirstImage: String) {
        LogUtils.i("=====" + mFirstImage)
        var bitmap: Bitmap = BitmapUtil.getBitmapFromSDCard(mFirstImage)
        val dm = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(dm)
        screen_width = dm.widthPixels
        screen_height = dm.heightPixels
        if (bitmap != null) {
            bitmap = resizeSurfaceWithScreen(bitmap, screen_width, screen_height)
            val degree: Int = readPictureDegree(mFirstImage)
            bitmap = rotaingImageView(degree, bitmap)
            mViewBinding.civ.setImageBitmap(bitmap)
            mViewBinding.ivTest.setImageBitmap(mViewBinding.civ.imageBitmap)
        } else {
            ToastUtils.showShort("文件有误，请重试")
            LogUtils.i("bitmap == null")
        }
        //比例
        mViewBinding.civ.setFixedAspectRatio(mAspectRatioX != 0) //任意大小的裁剪
        if (mAspectRatioX != 0) {
            mViewBinding.civ.setAspectRatio(mAspectRatioX, mAspectRatioY)
        }
    }

    /**
     *
     * @param angle
     * @param bitmap
     * @return Bitmap
     */
    private fun rotaingImageView(angle: Int, bitmap: Bitmap): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(angle.toFloat())
        val resizedBitmap =
            Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        return resizedBitmap
    }

    private fun readPictureDegree(path: String): Int {
        var degree = 0
        try {
            val exifInterface = ExifInterface(path)
            val orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION,
                ExifInterface.ORIENTATION_NORMAL
            )
            when (orientation) {
                ExifInterface.ORIENTATION_ROTATE_90 -> degree = 90
                ExifInterface.ORIENTATION_ROTATE_180 -> degree = 180
                ExifInterface.ORIENTATION_ROTATE_270 -> degree = 270
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return degree
    }

    private fun resizeSurfaceWithScreen(
        bitmap: Bitmap,
        screen_width: Int,
        screen_height: Int
    ): Bitmap {
        var bitmap = bitmap
        var width = bitmap.width
        var height = bitmap.height
        if (width < screen_width && height < screen_height) {
            val scale_width = screen_width * 1.0f / width
            val scale_height = screen_height * 1.0f / height
            val scale = if (scale_width > scale_height) scale_height else scale_width
            width = (width * scale).toInt()
            height = (height * scale).toInt()
        } else {
            if (width > screen_width) {
                height = height * screen_width / width
                width = screen_width
            }
            if (height > screen_height) {
                width = width * screen_height / height
                height = screen_height
            }
        }
        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false)
        bitmap = BitmapUtil.zoomBitmap(bitmap, width, height)

        val baos = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos)
        while (baos.toByteArray().size > 1024 * 1024) {
            baos.reset()
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
        }
        val isBm = ByteArrayInputStream(baos.toByteArray())
        val bitmap_new = BitmapFactory.decodeStream(isBm, null, null)
        return bitmap_new!!
    }
}